<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../../styles/prod.scss";
</style>
<template>
  <div class="app-container calendar-list-container">
    <!-- 基本属性 -->
    <custom-card title="申请信息">
      <template>
        <el-form :model="postForm" ref="postForm" label-suffix="：" label-width="120px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="申请类型" prop="applyTypeId" required>
                <el-select v-model="postForm.applyTypeId" placeholder="请选择" style="width:100%;">
                  <el-option v-for="item in typeList" :key="item.id" :label="language=='en'?item.labelEnUs:item.labelZhCh" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="postForm.id">
              <el-form-item label="申请人" prop="name">
                <el-input :value="postForm.createUserName" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="postForm.id">
              <el-form-item label="申请部门" prop="name">
                <el-input :value="postForm.createUserDepart" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="项目编号" prop="projectNo" required>
                <el-input v-model="postForm.projectNo" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品型号" prop="plmModelNo" required>
                <el-select v-model="postForm.plmModelNo" placeholder="请选择" style="width:100%;" @change="selectModel">
                  <el-option v-for="item in modelInfoList" :key="item.id" :label="item.plmModelNo" :value="item.plmModelNo">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="postForm.productName" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="主办业务人" prop="hostingBusiness" required>
                <el-select v-model="postForm.hostingBusiness" filterable remote :placeholder="'请选择'"  :remote-method="getHostingName">
                  <el-option v-for="option in hostingBusinessList" :key="option.id" :label="option.name" :value="option.username">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="申请原因" prop="applyReason" required>
            <el-input v-model="postForm.applyReason" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="证书种类">
            <el-row>
              <el-col v-for="(item, index) in certCategoryList" :key="'cert' + index" :span="item.categoryType ? 12 : 6">
                <el-checkbox v-model="item.isChecked" style="width: 50%">{{item.name}}</el-checkbox>
                <el-input v-if="item.categoryType" v-model="item.remark" size="mini" style="width: 40%;"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-row>
            <el-col :span="6">
              <el-form-item label="客户编号" prop="customerNo" required>
                <el-input v-model="postForm.customerNo" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户型号" prop="customerModelNo" required>
                <el-input v-model="postForm.customerModelNo" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="币别" prop="currencyDv">
                <el-select v-model="postForm.currencyDv" placeholder="请选择" style="width:100%;">
                  <el-option v-for="item in currencyList" :key="item.id" :label="language=='en'?item.labelEnUs:item.labelZhCh" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="预计费用" prop="estimatedCost">
                <el-input v-model="postForm.estimatedCost" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="持证单位" prop="certLicensedUnitId" required>
            <el-select v-model="postForm.certLicensedUnitId" placeholder="请选择" @change="selectUnit">
              <el-option v-for="item in unitList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="持证单位名称">
            <el-input :value="unitObj.companyName || ''" readonly></el-input>
          </el-form-item>
          <el-form-item label="持证单位地址">
            <el-input :value="unitObj.companyAddress" readonly></el-input>
          </el-form-item>
          <el-form-item label="费用承担方">
          </el-form-item>
          <el-row>
            <el-col :span="6" :offset="1">
              <el-form-item label="亚特比例" prop="costBearerYat" required>
                <el-input v-model="postForm.costBearerYat" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户比例" prop="costBearerCustomer" required>
                <el-input v-model="postForm.costBearerCustomer" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商比例" prop="costBearerSupplier" required>
                <el-input v-model="postForm.costBearerSupplier" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="样品预计完成日期" label-width="150px">
            <el-date-picker v-model="postForm.sampleEndDate" placeholder="请选择" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
          <el-form-item label="申请要求完成日期" prop="applyEndDate" label-width="150px" required>
            <el-date-picker v-model="postForm.applyEndDate" placeholder="请选择" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
          <el-row>
            <el-col :span="6">
              <el-form-item label="账套" prop="books" required>
                <el-select v-model="postForm.books" placeholder="请选择">
                  <el-option v-for="item in booksList" :key="item.id" :label="item.name" :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="主办工程师" prop="engineer" required>
                <el-select v-model="postForm.engineer" filterable remote :placeholder="'请选择'"  :remote-method="getEngineerByName">
                  <el-option v-for="option in engineerList" :key="option.id" :label="option.name" :value="option.username">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="地区" prop="certArea">
                <el-input v-model="postForm.certArea"  placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="参数" prop="params">
                <el-input v-model="postForm.params" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </custom-card>
    <div class="pds-btm mt-30">
      <!-- <div v-if="postForm.id && postForm.status == 0">
        已保存草稿
        <span class="tip">{{postForm.updateTime | formatTime}}</span>
      </div> -->
      <div class="right">
        <el-button class="filter-item" type="default" @click="cancel()">取消</el-button>
        <el-button class="filter-item" type="warning" :loading="loading" :disabled="loading" @click="validateForm(0)">保存草稿</el-button>
        <el-button class="filter-item" type="primary" :loading="loading" :disabled="loading" @click="validateForm(1)">提交</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import {
  mapGetters
} from 'vuex';
import * as baseApi from '@/api/common/index'
import * as prodApi from '@/api/product/index'
import * as planApi from '@/api/cert/plan/index'
import BasicForm from '@/components/BasicForm/index'
import CustomCard from '@/components/CustomCard/index'
import UploadList from '@/components/UploadList/index'
export default {
  name: 'user',
  components: {
    BasicForm,
    CustomCard,
    UploadList
  },
  data() {
    return {
      loading: false,
      formId: 0,
      postFormInit: {
        applyEndDate: "",
        applyReason: "",
        applyTypeId: null,
        certLicensedUnitId: null,
        books: null,
        costBearerCustomer: null,
        costBearerSupplier: null,
        costBearerYat: null,
        currencyDv: "",
        customerModelNo: "",
        customerNo: "",
        estimatedCost: null,
        hostingBusiness: "",
        pdsCertApplyCategoriesList: [],
        plmModelNo: "",
        productName: "",
        projectNo: "",
        sampleEndDate: "",
        cert_area: "",
        params: "",
        status: 0
      },
      postForm: {},
      typeList: [],
      modelInfoList: [],
      currencyList: [],
      certCategoryList: [],
      unitList: [],
      booksList: [],
      engineerList: [],
      hostingBusinessList: [],
      unitObj: {}
    }
  },
  created() {
    this.getOptions()
  },
  // activated() {
  //   if (this.$route.query.id) {
  //     if (!this.formId || this.$route.query.id != this.formId) {
  //       this.formId = this.$route.query.id || 0;
  //       this.getDetail();
  //     }
  //   }
  // },
  computed: {
    ...mapGetters([
      'elements',
      'language'
    ])
  },
  methods: {
    /* 页面刷新初始化 */
    refresh() {
      if (this.$route.query.id) {  /* 编辑 */
        this.getDetail();
        /* 清空表单验证状态 */
        setTimeout(() => {
          this.$refs.postForm.clearValidate();
        })
      } else {  /* 添加 */
        this.postForm = JSON.parse(JSON.stringify(this.postFormInit));
        setTimeout(() => {
          this.$refs.postForm.clearValidate();
        })
      }
    },
    // 获取工程师
    getEngineerByName(val) {
      if (val !== '') {
        prodApi.getEngineerByName({
          name: val
        })
          .then(res => {
            this.engineerList = res.data;
          });
      }
    },
        // 获取主办业务人
    getHostingName(val) {
      if (val !== '') {
        prodApi.getEngineerByName({
          name: val
        })
          .then(res => {
            this.hostingBusinessList = res.data;
          });
      }
    },
    /* 获取配置项 */
    getOptions() {
      /* 产品类型 */
      baseApi.getTypeValue('cert_dict_apply_type').then(res => {
        this.typeList = res.data.rows;
      })
      /* 产品型号 */
      planApi.getPdsFileModelInfo().then(res => {
        this.modelInfoList = res.data;
      })
      /* 认证类型 */
      prodApi.certList().then(res => {
        this.certCategoryList = res.data;
      })
      /* 币别 */
      baseApi.getTypeValue('cert_dict_currency').then(res => {
        this.currencyList = res.data.rows;
      })
      /* 持证信息 */
      prodApi.unitList().then(res => {
        this.unitList = res.data;
      })
      /* 账套 */
      prodApi.booksList().then(res => {
        this.booksList = res.data;
      })

    },
    getDetail() {
      planApi.getCertPlanDetail(this.$route.query.id).then(res => {
        if (res.code == 200) {
          this.postForm = res.data.pdsCertApply;
          this.postForm.pdsCertApplyCategoriesList = res.data.pdsCertApplyCategoriesList;
          /* 认证类型 */
          if (this.postForm.pdsCertApplyCategoriesList.length) {
            this.certCategoryList.map((item, index) => {
              this.$set(this.certCategoryList[index], 'isChecked', false);
              this.postForm.pdsCertApplyCategoriesList.map(subItem => {
                if (item.id == subItem.certCategoryId) {
                  this.$set(this.certCategoryList[index], 'isChecked', true);
                  if (item.categoryType) {
                    item.remark = subItem.remark;
                  }
                }
              })
            })
          }
          /* 回显 */
          if (this.postForm.certLicensedUnitId) {
            this.selectUnit(this.postForm.certLicensedUnitId);
          }
          let engineerName = ""
          let hostingBusinessName = ""
          if (res.data.pdsCertApply.engineerName) engineerName = res.data.pdsCertApply.engineerName;   
            this.getEngineerByName(engineerName)
          if (res.data.pdsCertApply.hostingBusinessName) hostingBusinessName = res.data.pdsCertApply.hostingBusinessName;   
            this.getHostingName(hostingBusinessName)
        }
      })
    },
    /* 选中认证类型 */
    selectCert(value, index) {
      this.$set(this.certCategoryList[index], 'isChecked', value);
    },
    /* 产品型号 */
    selectModel(value) {
      this.modelInfoList.map(item => {
        if (item.plmModelNo == value) {
          this.postForm.productName = item.name;
        }
      })
    },
    /* 选中持证公司 */
    selectUnit(value) {
      this.unitList.map(item => {
        if (item.id == value) {
          this.unitObj = item;
        }
      })
    },
    validateForm(type) {
      this.postForm.status = type;
      if (type) { /* 提交 */
        this.$refs.postForm.validate(valid => {
          if (valid) {
            let flag = false;
            for (let i = 0; i < this.certCategoryList.length; i++) {
              if (this.certCategoryList[i].isChecked) {
                flag = true;
              }
              if (this.certCategoryList[i].categoryType && this.certCategoryList[i].isChecked && !this.certCategoryList[i].remark) {
                this.$message.info('请填写已选认证类型的备注');
                return;
              }
            }
            if (!flag) {
              this.$message.info('请选择认证类型')
              return;
            }
            this.submitForm();
          } else {
            this.$message.info('请将信息填写完整');
          }
        })
      } else {  /* 草稿 */
        if (!this.postForm.applyTypeId) {
          this.$message.info('请选择申请类型')
          return;
        }
        if (!this.postForm.projectNo) {
          this.$message.info('请填写项目编号')
          return;
        }
        this.submitForm();
      }
    },
    submitForm() {
      this.loading = true;
      let certList = [];
      this.certCategoryList.map(item => {
        if (item.isChecked) {
          item.certCategoryId = item.id;
          certList.push(item);
        }
      })
      this.postForm.pdsCertApplyCategoriesList = certList;
      console.log('asdasd',this.postForm);
      planApi.saveCertPlan(this.postForm).then(res => {
        if (res.code === 200) {
          this.$message.success((this.postForm.status ? '提交' : '保存草稿') + '成功')
          this.$store.commit('ADD_LIST_REFRESH', this.$route.path.slice(0,this.$route.path.lastIndexOf('/')));
          if (this.postForm.status) {
            this.$store.dispatch('delActiveViews');
          }
        } else {
          this.$message.warning((this.postForm.status ? '提交' : '保存草稿') + '失败')
        }
        this.loading = false;
      }).catch(err => {
        console.log(err);
        this.loading = false;
      })
    }
  }
}
</script>
